package com.bing.index;

import java.awt.image.BufferedImage;
import java.io.IOException;

import javax.imageio.ImageIO;

import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.IndexWriter;

import com.bing.document.GlobalDocumentBuilderFactory;
import com.bing.document.GlobalFeature;
import com.bing.index.writer.IndexWriterFactory;
import com.bing.picture.Picture;

public class DefaultIndexCreator implements IndexCreator {
	
	@Override
	public void createIndex(Picture picture) {
		this.createIndex(picture, new IndexWriterFactory("index").getIndexWriter());
	}

	@Override
	public void createIndex(Picture picture, IndexWriter indexWriter) {
		this.createIndex(picture, indexWriter, GlobalFeature.LBP);
	}

	@Override
	public void createIndex(Picture picture, IndexWriter indexWriter, GlobalFeature globalFeature) {
		this.createIndex(picture, indexWriter, globalFeature.getGlobalFeatureClazz());
	}

	@Override
	public void createIndex(Picture picture, IndexWriter indexWriter,
			Class<? extends net.semanticmetadata.lire.imageanalysis.features.GlobalFeature> globalFeatureClass) {
		
		BufferedImage img;
		try {
			img = ImageIO.read(picture.pictureInputStream());
			Document document = GlobalDocumentBuilderFactory.instance().getGlobalDocumentBuilder(globalFeatureClass).createDocument(img, picture.pictureUrl());
			document.add(new Field("pk", picture.pk(), TextField.TYPE_STORED));
			document.add(new Field("url", picture.pictureUrl(), TextField.TYPE_STORED));
			indexWriter.addDocument(document);
			indexWriter.commit();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public boolean hasCreate() {
		return false;
	}

}
